package com.lxy.aimin.ai.controller;


import com.aliyuncs.exceptions.ClientException;
import com.lxy.aimin.ai.service.RagService;
import com.lxy.aimin.base.response.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {


    private final VectorStore vectorStore;
    private final RagService ragService;

    /**
     * 上传并读取文件内容，保存到向量存储中
     * @param file 上传的文件（支持pdf/word/txt）
     * @return 处理结果
     */
    @PostMapping("/upload")
    public Result<String> uploadAndLoadData(@RequestParam("file") MultipartFile file) throws IOException, ClientException {
        boolean success = ragService.uploadAndLoadData(file);
        return success ? Result.success() : Result.error("处理失败");
    }

    @GetMapping("/search")
    public Result<?> search(String question) {

        SearchRequest searchRequest = SearchRequest.builder()
                .query(question)
                .similarityThreshold(0.4)  //按照阈值做相似查询
                .topK(10)   //查询前？条
                .build();

        List<Document> documents = vectorStore.similaritySearch(searchRequest);
        // 我眼睛疼 0.4498

        assert documents != null;
        System.out.println("搜索到文档数量:" +documents.size());
        for(Document document : documents) {
            System.out.println(document.getText());
        }
        return Result.success();
    }


}
